<template>
  <div class="divWarehouse divCheckTaskComponent">
    <div class="divHead box">
      <div class="serchForm">
        <el-row :gutter="30">
          <el-col :span="8">
            <div class="divLable">盘点编号</div>
            <el-input
              v-model="searchParams.checkCode"
              placeholder="请输入"
              clearable
            />
          </el-col>
          <el-col :span="8">
            <div class="divLable">任务状态</div>
            <el-select
              v-model="searchParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <div class="divLable">盘点类型</div>
            <el-select
              v-model="searchParams.type"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in typeSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div class="textRight">
        <base-button
          class="minorImportantButton btnSearch"
          @click="btnSearchClick"
        >搜索</base-button>
        <base-button class="unimportanceButton" @click="btnResetClick">重置</base-button>
      </div>
    </div>
    <div class="divContent box">
      <div class="tableInfo">
        <base-button
          class="importantButton"
          @click="btnBatchClick([],'loseProfit')"
        >生成损益单</base-button>
                <base-button
          class="unimportanceButton"
          @click="btnBatchClick([],'')"
        >生成复盘</base-button>
      </div>
      <div  v-if="tableData.length>0">
        <el-table
          :data="tableData"
          stripe
          border
          ref="taskTable"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#f9f6ee' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            type="index"
            align="center"
            width="68"
            label="序号"
          />
          <el-table-column
            prop="checkCode"
            align="center"
            label="盘点单号"
            width="160"
          />
          <el-table-column
            prop="code"
            align="center"
            label="任务编号"
            width="150"
          />
          <el-table-column
            prop="status"
            align="center"
            label="任务状态"
            width="160"
            :filters="[{text: '待分配', value: 1}, {text: '盘点中', value: 2}, {text: '盘点已完成', value: 3}, {text: '已生成损益', value: 4}, {text: '完成盘点', value: 5}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
              <span v-if="row.status === 1">待分配</span>
              <span v-if="row.status === 2">盘点中</span>
              <span v-if="row.status === 3">盘点已完成</span>
              <span v-if="row.status === 4">已生成损益</span>
              <span v-if="row.status === 5">完成盘点</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            width="200"
            sortable
          />
          <el-table-column
            prop="planTaskTime"
            align="center"
            label="计划作业时间"
            width="200"
            sortable
          />
          <el-table-column
            prop="ownerName"
            align="center"
            label="货主"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="dimension"
            align="center"
            label="盘点维度"
            width="160"
          >
            <template slot-scope="{row}">
              <span v-if="row.dimension === 'KW'">库位</span>
              <span v-if="row.dimension === 'HP'">货品</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="type"
            align="center"
            label="盘点类型"
            width="160"
          >
            <template slot-scope="{row}">
              <span v-if="row.type === 'SJPD'">随机盘点</span>
              <span v-if="row.type === 'JHPD'">计划盘点</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouseName"
            align="center"
            label="仓库"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="areaName"
            align="center"
            label="库区"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="stockTotal"
            align="center"
            label="库存总数"
            width="160"
          />
          <el-table-column
            prop="checkNum"
            align="center"
            label="盘点次数"
            width="180"
            :filters="[{text: '一盘', value: 1}, {text: '复盘', value: 2}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
                <span v-if="row.checkNum === 1">一盘</span>
                <span v-if="row.checkNum === 2">复盘</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="personName"
            align="center"
            label="盘点人"
            width="180"
          />
          <el-table-column
            prop="checkTotal"
            align="center"
            label="盘点总数"
            width="180"
          />
          <el-table-column
            prop="differenceNum"
            align="center"
            label="差异合计"
            width="180"
          />
          <el-table-column
            prop="createName"
            align="center"
            label="创建人"
            width="180"
          />
          <el-table-column label="操作" align="center" width="250" fixed="right">
            <template slot-scope="{row}">
              <base-button class="fontOperateButton" v-if="row.status ===1" @click="btnDistributeClick(row.id)">分配</base-button>
              <base-button class="fontOperateButton" v-if="row.status > 2" @click="btnAddCheckClick(row.masterId,row.checkNum,0)">查看详情</base-button>
              <base-button class="fontOperateButton" v-if="row.status ===2" @click="btnAddCheckClick(row.masterId,row.checkNum,1)">盘点录入</base-button>
              <base-button class="fontOperateButton" v-if="row.status ===2" @click="btnFinishCheck([row.id])">完成盘点</base-button>
              <base-button class="fontOperateButton" v-if="row.status ===3 && row.differenceNum !== 0" @click="btnBatchClick([row.id],'loseProfit')">生成损益</base-button>
              <base-button class="fontOperateButton" v-if="row.status ===3 && row.checkNum === 1 && row.differenceNum !== 0" @click="btnBatchClick([row.id],'')">生成复盘</base-button>
              <base-button class="fontOperateButton" v-if="row.status ===4 && row.differenceNum !== 0 " @click="btnViewLoseProfitClick(row)">查看损益明细</base-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
      <base-pagination :total="paging.total" :limit="paging.size" @current-change="handleCurrentChange"  @size-change="handleSizeChange"></base-pagination>
      </div>
      <div
        v-else
        class="emptyTip"
      >
        <span class="imgIcon"></span>
        <p>暂无盘点任务</p>
      </div>
    </div>
    <distribute-user-dialog   :visible="distributeUserDialogData.visible"
                              @handlesubmit="handlesubmit"
                              @handleclose ="distributeUserDialogData.visible = false">
    </distribute-user-dialog>
    <base-dialog  :title="dialogData.title"
                    :visible="dialogData.visible"
                    :msg="dialogData.msg"
                    :subMsg="dialogData.subMsg"
                    @btn-cancle-click="dialogData.visible= false"
                    @btn-sure-click ="btnSureClick"
    ></base-dialog>
    <base-list-dialog :visible="batchDialogData.visible"
                      :title="batchDialogData.title"
                      :subTitle="batchDialogData.subTitle"
                      :msg="batchDialogData.msg"
                      :itemList="batchDialogData.itemList"
                      :msgFailure="batchDialogData.msgFailure"
                      :itemListFailure="batchDialogData.itemListFailure"
                      @btn-sure-click="btnBatchSureClick"
                      >
    </base-list-dialog>
      <el-dialog
        :title="loseProfitDialogData.title"
        :visible.sync="loseProfitDialogData.visible"
        width="50%" class="divLoseProfit">
        <div  v-if="loseProfitDialogData.tableData.length>0">
          <el-table
            :data="loseProfitDialogData.tableData"
            stripe
            border
            style="width: 100%"
            :header-cell-style="{ background: '#f9f6ee' }"
          >
            <el-table-column
              type="index"
              align="center"
              width="68"
              label="序号"
            />
            <el-table-column
              prop="code"
              align="center"
              label="损益单号"
              width="160"
            />
            <el-table-column
              prop="warehouseName"
              align="center"
              label="仓库名称"
              width="150"
            />
            <el-table-column
              prop="areaName"
              align="center"
              label="库区名称"
              width="160"
            >
            </el-table-column>
            <el-table-column
              prop="locationName"
              align="center"
              label="库位名称"
              width="160"
            />
            <el-table-column
              prop="ownerName"
              align="center"
              label="货主名称"
              width="160"
            />
            <el-table-column
              prop="goodsName"
              align="center"
              label="货品名称"
              width="160"
            />
            <el-table-column
              prop="idNum"
              align="center"
              label="损益数量"
              width="160"
            />
            <el-table-column
              prop="idMoney"
              align="center"
              label="损益金额(元)"
              width="160"
            >
            </el-table-column>
            <el-table-column
              prop="updateTime"
              align="center"
              label="处理时间"
              width="200"
              sortable

            >
            </el-table-column>
            <el-table-column
              prop="status"
              align="center"
              label="损益单状态"
              width="160"
            >
              <template slot-scope="{row}">
                <span v-if="row.status === 1">新建</span>
                <span v-if="row.status === 2">已调整</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <base-button class="minorImportantButton" @click="loseProfitDialogData.visible = false">确 定</base-button>
        </span>
      </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import BaseButton from '@/components/base-button/index.vue'
import { ICheckTaskTableData } from '@/module-storage/interface/check-task'
import { ILoseProfitTableData } from '@/module-storage/interface/lose-profit'
import BasePagination from '@/components/base-pagination/index.vue'
import {
  createDoubleCheckTask,
  createLoseProfit,
  distributeCheckTask,
  findCheckTaskDetailPaging,
  finishCheckTask
} from '@/module-storage/api/check-task'
import { checkTypeOptions, checkTaskStatusOptions } from '@/utils/common-select-data'
import { ICommonReturn, ICommonSelectOptions, ICommonSelectOptionsString } from '@/utils/common-interface'
import DistributeUserDialog from '@/components/base-allocation/index.vue'
import BaseDialog from '@/components/base-dialog/index.vue'
import BaseListDialog from '@/components/base-dialog/index1.vue'
import { findAllLoSeProfitDetailPaging } from '@/module-storage/api/lose-profit'

@Component({
  name: 'CheckTask',
  components: {
    BaseButton,
    BasePagination,
    DistributeUserDialog,
    BaseDialog,
    BaseListDialog
  }
})

export default class extends Vue {
  private tableData: ICheckTaskTableData[] = []
  private statusSelectOptions:ICommonSelectOptions[] = []
  private typeSelectOptions:ICommonSelectOptionsString[] = []
  private loading = false
  private searchParams = {
    checkCode: '',
    status: undefined,
    type: undefined
  }

  private dialogData ={
    ids: [] as number[],
    title: '',
    visible: false,
    msg: '',
    subMsg: ''
  }

  private paging = {
    current: 1, // 当前页码
    size: 10, // 每页数据量
    total: 0
  }

  private distributeUserDialogData={
    id: 0,
    visible: false,
    name: ''
  }

  private batchDialogData = {
    ids: [] as number[],
    title: '',
    subTitle: '',
    msg: '',
    itemList: [] as string[],
    visible: false,
    msgFailure: '',
    itemListFailure: [] as string[],
    type: 'loseProfit'// 表示损益，其他的表示复盘
  }

  private loseProfitDialogData = {
    title: '损益详情',
    tableData: [] as ILoseProfitTableData[],
    paging: {
      current: 1, // 当前页码
      size: 10, // 每页数据量
      total: 0
    },
    visible: false
  }

  @Watch('$route', { immediate: true })
  private onRouteChange() {
    this.getList()
  }

  mounted() {
    this.statusSelectOptions = checkTaskStatusOptions
    this.typeSelectOptions = checkTypeOptions
  }

  private btnDistributeClick(id:number) {
    this.distributeUserDialogData.id = id
    this.distributeUserDialogData.visible = true
  }

  private btnSearchClick() {
    this.getList()
  }

  private btnResetClick() {
    this.searchParams = {
      checkCode: '',
      status: undefined,
      type: undefined
    }
    this.getList()
  }

  private getParams() {
    const current = this.paging.current
    const size = this.paging.size
    const params = {
      ...this.searchParams,
      current,
      size
    }
    if (params.status === '') {
      delete params.status
    }
    if (params.type === '') {
      delete params.type
    }
    return params
  }

  private async getList() {
    this.loading = true
    const params = this.getParams()
    const { data } = await findCheckTaskDetailPaging(params)
    this.loading = false
    this.tableData = data.records
    this.paging.total = parseInt(data.total, 10)
  }

  private handleCurrentChange(page:number) {
    this.paging.current = page
    this.getList()
  }

  private handleSizeChange(page:number) {
    this.paging.size = page
    this.paging.current = 1
    this.getList()
  }

  private async handlesubmit() {
    const distributeUserDialogData = this.distributeUserDialogData
    if (!distributeUserDialogData.name) {
      this.$message.error('请选择分配')
    } else {
      const data = ((await distributeCheckTask({
        id: distributeUserDialogData.id,
        personName: distributeUserDialogData.name
      })) as unknown) as ICommonReturn
      if (data.code === 0) {
        this.$message.success('分配成功')
        this.getList()
        this.distributeUserDialogData.visible = false
      } else {
        this.$message.error(data.msg)
      }
    }
  }

  private btnAddCheckClick(id:number, checkNum:number, edit:number) {
    const editStr = edit === 1 ? '' : '&null'
    this.$router.push({ path: `list-task/details/${id + '&' + checkNum + '&' + edit + editStr}` })
  }

  private btnFinishCheck(id:number[]) {
    this.dialogData = {
      ids: id,
      title: '盘点完成',
      visible: true,
      msg: '确认盘点完成吗？',
      subMsg: '完成后不能修改盘点结果'
    }
  }

  private async btnSureClick() {
    this.dialogData.visible = false
    const { data } = await finishCheckTask(this.dialogData.ids)
    const errors = data.errors as string[]
    const results = data.results as string[]
    if (errors.length > 0) {
      this.$message.error(errors[0])
    }
    if (results.length > 0) {
      this.$message.success('盘点成功')
      this.getList()
    }
  }

  private btnBatchSureClick() {
    this.batchDialogData.visible = false
    this.batchDialogData.ids = []
  }

  private handleSelectionChange(itemList:ICheckTaskTableData[]) {
    this.batchDialogData.ids = itemList.map(item => {
      return item.id
    })
  }

  // 生成损益单和生成复盘的点击事件
  private async btnBatchClick(ids:number[], type:string) {
    if (ids.length > 0) {
      this.batchDialogData.ids = ids
    }

    const batchDialogData = this.batchDialogData
    if (batchDialogData.ids.length === 0) {
      this.$message.error('请选择盘点任务')
      return
    }
    this.batchDialogData = {
      ids: [] as number[],
      title: '损益单生成',
      subTitle: '',
      msg: '',
      itemList: [] as string[],
      visible: true,
      msgFailure: '',
      itemListFailure: [] as string[],
      type: ''
    }
    if (type === 'loseProfit') { // 损益
      const { data } = await createLoseProfit(batchDialogData.ids)
      const errors = data.errors as string[]
      const results = data.results as string[]
      if (results.length > 0) {
        this.batchDialogData.msg = '损益单编号如下，请在库存损益中查看'
        this.batchDialogData.itemList = results
        this.batchDialogData.subTitle = results.length + '个损益单生成成功！'
        this.getList()
      }

      if (errors.length > 0) {
        if (errors.length > 0) {
          this.batchDialogData.msgFailure = '损益单生成失败原因如下'
        }
        this.batchDialogData.itemListFailure = errors
        this.batchDialogData.subTitle += (errors.length + '个损益单生成失败！')
      }
    } else {
      const { data } = await createDoubleCheckTask(batchDialogData.ids)
      const errors = data.errors as string[]
      const results = data.results as string[]
      if (results.length > 0) {
        this.batchDialogData.msg = '复盘任务编号如下,请在盘点任务中查看'
        this.batchDialogData.itemList = results
        this.batchDialogData.subTitle = results.length + '个复盘任务生成成功！'
        this.getList()
      }

      if (errors.length > 0) {
        if (errors.length > 0) {
          this.batchDialogData.msgFailure = '复盘任务生成失败原因如下'
        }
        this.batchDialogData.itemListFailure = errors
        this.batchDialogData.subTitle += (errors.length + '个复盘任务生成失败！')
      }
    }
    (this.$refs.taskTable as any).clearSelection()
  }

  private async btnViewLoseProfitClick(row:ICheckTaskTableData) {
    const current = this.loseProfitDialogData.paging.current
    const size = this.loseProfitDialogData.paging.size
    const { data } = await findAllLoSeProfitDetailPaging({
      current, size, taskCode: row.code
    })
    this.loseProfitDialogData.tableData = data.records
    this.loseProfitDialogData.paging.total = parseInt(data.total, 10)
    this.loseProfitDialogData.visible = true
  }

  private filterHandler(value:any, row:any, column:any) {
    const property = column.property
    return row[property] === value
  }
}
</script>
<style lang="scss" scoped>
.divCheckTaskComponent{
  height: auto;
}
</style>
